<template>
  <div>
    <div>
      <!-- 添加标签 -->
      <el-dialog title="告警详情" :visible.sync="dialogFormVisible">
        <el-form :model="searchRes">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="searchRes.targetName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="证件号" :label-width="formLabelWidth">
            <el-input v-model="searchRes.idCard" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="抓拍时间" :label-width="formLabelWidth">
            <el-input v-model="searchRes.createdAt" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="抓拍地址" :label-width="formLabelWidth">
            <el-input v-model="searchRes.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-input v-if="searchRes.sex===1" value="男"  autocomplete="off">
            <el-input v-if="searchRes.sex===2" value="女"  autocomplete="off">
            </el-input>
            </el-input>
          </el-form-item>
          <el-form-item label="年龄" :label-width="formLabelWidth">
            <el-input v-model="searchRes.age" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="眼镜" :label-width="formLabelWidth">
              <el-input v-if="searchRes.glasses===1" value="戴眼镜"  autocomplete="off">
              <el-input v-if="searchRes.glasses===2" value="不戴眼镜"  autocomplete="off">
            </el-input>
          </el-input>
          </el-form-item>
          <el-form-item label="口罩" :label-width="formLabelWidth">
                <el-input v-if="searchRes.mask===1" value="戴口罩"  autocomplete="off">
                  <el-input v-if="searchRes.mask===2" value="不戴口罩"  autocomplete="off">
                </el-input>
            </el-input>
          </el-form-item>
          <el-form-item label="帽子" :label-width="formLabelWidth">
                <el-input v-if="searchRes.hat===1" value="戴帽子"  autocomplete="off">
                  <el-input v-if="searchRes.hat===2" value="不戴帽子"  autocomplete="off">
                  </el-input>
                </el-input>
          </el-form-item>
            <el-form-item label="拍照人脸" :label-width="formLabelWidth">
              <img :src="searchRes.img">
            </el-form-item>
            <el-form-item label="目标人脸" :label-width="formLabelWidth">
              <img :src="searchRes.img">
            </el-form-item>
          <div id="container" style="width: 100%; height: 900px;"></div>
          </el-form>

        <div>
          <el-form :inline="true" :model="searchObj" class="demo-form-inline">
            <el-form-item label="开始时间">
              <el-input v-model="searchObj.tagName" placeholder="开始时间"></el-input>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-input v-model="searchObj.tagName" placeholder="结束时间"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-form :inline="true" :model="searchObj" class="demo-form-inline">
        <el-form-item label="标签名称">
          <el-input v-model="searchObj.tagName" placeholder="标签名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="编号" show-overflow-tooltip></el-table-column>
      <el-table-column prop="targetName" label="姓名" show-overflow-tooltip></el-table-column>
      <el-table-column prop="img" label="照片" show-overflow-tooltip>
        <template v-slot="scope">
          <el-image :src="scope.row.img"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="idCard"  label="证件号码" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createdAt" label="抓拍时间" show-overflow-tooltip></el-table-column>
      <el-table-column prop="address" label="抓拍地点" show-overflow-tooltip></el-table-column>
      <el-table-column prop="task" label="所属任务" show-overflow-tooltip></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="150">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row.id)" type="text" size="small"><i class="el-icon-edit"></i>查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-col
        v-for="(residence, index) in tableData"
        :key="residence.id"
        :span="6"
        :offset="index > 0 ? 2 : 0"
      >
        <el-card
          class="card-container"
          :class="{ 'card-selected': selectedResidenceIndex === index }">
          <div
            style="width: 100%;height: 100%;"
          >
            <div class="card-content">
              <div class="image-wrapper">
                <img
                  :src="residence.img"
                  class="image"
                  style="width: 150px;height: 500px"
                >
                <span class="title" style="font-size: 15px;">比对:{{ residence.controst}}</span>
                <img
                  :src="'https://mall-cjq.oss-cn-shanghai.aliyuncs.com/2024/NOVEMBER/24/15/1/3f0d7609-4cb0-450a-bd9a-718f325cd192.jpg'"
                  class="image"
                  style="width: 150px;height: 500px"
                >
                <br>
                编号：{{ residence.id }}
              </div>
              <div class="info-wrapper">
                <span class="title" style="font-size: 20px">{{ residence.name }}</span>
                <span class="title">{{ residence.address }}</span>
                <div class="bottom-info clearfix" style="margin-top: 10px;margin-bottom: 10px">
                  <b style="margin-right: 10px;">辖区：</b>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </div>
    <!--    分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchObj.pageNum"
      :page-sizes="[5, 10, 20, 100]"
      :page-size="searchObj.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import {getWarningMessageById, getWarningMessageList} from "../../../api/monitor/warning";
export default {
  data() {
    return {
      total: 0,
      tableData:[],
      searchObj:{
        pageNum:1,
        pageSize:20,
      },
      searchRes:{
        targetName:'',
        idCard:'',
        createdAt:'',
        address:'',
        sex:'',
        age:'',
        glasses:'',
        mask:'',
        hat:'',
      },
      warnings:{
        id:'',
        targetName:'',
        img:'',
        idCard:'',
        createdAt:'',
        address:'',
        task:'',
      },
      selectedResidenceIndex: 0,
      multipleSelection: [],
      options:[],
      dialogFormVisible: false,
      formLabelWidth: '120px',

      map: null,
      polygon1: null,
      polygon2: null,
      polyEditor: null,
      //data中定义变量
      lockReconnect: false,
      wsCfg: {
        // websocket地址(需要更改连接地址)
        url: "ws://localhost:8080/report-emergency/ws/test"
      },
      socket:null,
      warningId:"",
    }
  },
  created() {
    this.socket = new WebSocket(this.wsCfg.url)
    this.createWebSocket()
    // 标签列表
    this.getList()
    // 标签分组
    this.getTagList()
    this.initMap();
  },
  methods:{
    createWebSocket: function() {
      console.log('createWebSocket')
      try {
        // 创建Web Socket 连接
        // this.socket = new WebSocket(this.wsCfg.url)
        // 初始化事件
        this.initEventHandle(this.socket)
      } catch (e) {
        // 出错时重新连接
        console.log(e)
        this.reconnect(this.wsCfg.url)
      }
    },
    initEventHandle(socket) {
      // 连接关闭时触发
      socket.onclose = () => {
        console.log("连接关闭");
      };
      // 通信发生错误时触发
      socket.onerror = () => {
        // 重新创建长连接
        this.reconnect();
      };
      // 连接建立时触发
      socket.onopen = () => {
        console.log("连接成功");
      };
      // 客户端接收服务端数据时触发
      socket.onmessage = msg => {
        // 业务逻辑处理
        try{
          this.warningId = msg.data
          console.log(this.warningId)
          // this.websocketSetFlag =	JSON.parse(msg.data).content;
          // console.log(this.websocketSetFlag )
        }catch{
          console.log('error')
        }
      };
    },
    reconnect() {
      //重连
      if (this.lockReconnect) {
        return;
      }
      this.lockReconnect = true;
      // 没连接上会一直重连，设置延迟避免请求过多
      setTimeout(() => {
        this.lockReconnect = false;
        this.createWebSocket(this.wsCfg.url);
      }, 2000);
    },
    sendWebsocket(text){
      //发送数据
      this.socket.send(
        JSON.stringify({
          type: "control",
          content: text,
        })
      ) ;
    },

    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchObj.pageSize=val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchObj.pageNum=val
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //标签列表展示
    getList() {
      getWarningMessageList(this.searchObj).then(
        res=>{
          this.tableData=res.data.list
          this.total=res.data.total
        }
      )
    },


    // 回显
    handleClick(id) {
      this.dialogFormVisible = true;
      getWarningMessageById(id).then(response => {
        this.searchRes = response.data;

      })
    },

    initMap() {
      AMapLoader.load({
        key: "6c1c7414bd81a86947bdf8ed66a9677b", // 使用环境变量存储API Key
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.ToolBar'] // 加载比例尺和工具栏插件
      }).then((AMap) => {
        this.map = new AMap.Map("container", {
          center: [121.801628, 31.062258],
          zoom: 16.8,
        });
        this.map.plugin(['AMap.MapType','AMap.Scale','AMap.HawkEye','AMap.PolygonEditor'],()=>{
          this.map.addControl(new AMap.MapType());
          this.map.addControl(new AMap.Scale());
          this.map.addControl(new AMap.HawkEye());
        });
        const path1 = [
          [116.475334, 39.997534],
          [116.476627, 39.998315],
          [116.478603, 39.99879],
          [116.478529, 40.000296],
          [116.475082, 40.000151],
          [116.473421, 39.998717],
        ];
        const path2 = [
          [116.474595, 40.001321],
          [116.473526, 39.999865],
          [116.476284, 40.000917],
        ];

        this.polygon1 = new AMap.Polygon({
          path: path1,
        });
        this.polygon2 = new AMap.Polygon({
          path: path2,
        });

        this.map.add([this.polygon1, this.polygon2]);
        this.map.setFitView();

        this.polyEditor = new AMap.PolygonEditor(this.map);
        this.polyEditor.addAdsorbPolygons([this.polygon1, this.polygon2]);

        this.polyEditor.on('add', (data) => {
          const polygon = data.target;
          this.polyEditor.addAdsorbPolygons(polygon);
          polygon.on('dblclick', () => {
            this.polyEditor.setTarget(polygon);
            this.openEditor();
          });
        });

        this.polygon1.on('dblclick', () => {
          this.polyEditor.setTarget(this.polygon1);
          this.openEditor();
        });

        this.polygon2.on('dblclick', () => {
          this.polyEditor.setTarget(this.polygon2);
          this.openEditor();
        });

        // 默认打开第二个多边形的编辑
        this.polyEditor.setTarget(this.polygon2);
        this.openEditor();
      }).catch(e => {
        // console.error("地图加载失败:", e);
        // alert("地图加载失败，请稍后重试。");
      });

    },

    createPolygon() {
      this.polyEditor.close();
      this.polyEditor.setTarget();
      this.openEditor();
    },
    openEditor() {
      this.polyEditor.open();
    },
    closeEditor() {
      this.polyEditor.close();
    },
    beforeDestroy() {
      if (this.map) {
        this.map.destroy(); // 销毁地图实例
      }
    }
  }
}
</script>

<style scoped lang="scss">
.card-container {
  height: 350px;
  width: 470px;
  display: flex;
  flex-direction: column; /* 保持卡片内容的垂直布局 */
  align-items: center; /* 如果需要，可以垂直居中 */
  justify-content: center; /* 如果需要，可以水平居中（但在这个案例中不是必需的） */
  padding: 16px; /* 给卡片内部添加一些内边距 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 添加卡片阴影，使样式更美观 */
  border-radius: 8px; /* 添加圆角 */
  background-color: #fff; /* 设置背景颜色 */
}

.card-selected {
  /* 选中卡片的样式，例如边框颜色变化、背景颜色变化等 */
  border: 2px solid #409EFF; /* Element UI的主题色 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center; /* 保持子元素垂直居中（在这个案例中可能不是必需的，因为我们有具体的布局） */
  width: 100%;
}

.image-wrapper {
  flex: 0 0 auto; /* 图片容器占据固定空间 */
  margin-right: 16px; /* 图片和信息之间的间距 */
}

.image {
  max-width: 150px; /* 限制图片的最大宽度 */
  max-height: 180px; /* 限制图片的最大高度，保持宽高比可以通过object-fit处理 */
  object-fit: cover; /* 保持图片的纵横比并填充容器 */
  border-radius: 8px; /* 添加圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加图片阴影 */
  /*限制图片于图片之间的距离*/
  margin-right: 50px;
}

.info-wrapper {
  flex: 1 1 auto; /* 信息容器占据剩余空间 */
  display: flex;
  flex-direction: column; /* 信息内容垂直排列 */
  align-items: flex-start; /* 信息内容从左侧开始排列 */
}

.title {
  font-size: 16px; /* 设置标题字体大小 */
  font-weight: bold; /* 设置标题字体加粗 */
  margin-bottom: 8px; /* 标题和底部信息之间的间距 */
}

.bottom-info {
  display: flex;
  align-items: center; /* 底部信息垂直居中 */
}

.time {
  margin-right: 16px; /* 时间和按钮之间的间距 */
  color: #999; /* 设置时间颜色 */
}

.operation-button {
  color: #409EFF; /* 设置按钮颜色 */
  text-decoration: none; /* 去除按钮的下划线 */
}

/* 其他样式可以根据需要调整 */
</style>
